
var getLinks = function()
{
	var inputs = document.getElementsByTagName('input');
	if(inputs.length == 0)
	{
		return;
	}

	var songs = [];
	var foundIndex = 1;
	for(var i=0; i<inputs.length; i++)
	{
		var input = inputs[i];
		if(input.type == 'hidden' && input.value.indexOf('.mp3,')>0)
		{
			var mp3 = input.value.split(',',2);
			var mp3id = input.id.substring(10); // audio_info
			var songDetails = input.parentNode.parentNode;

			var song = {
				id: mp3id,
				index: foundIndex++,
				path: mp3[0],
				artist: null,
				title: null,
				duration: parseInt(mp3[1]),
				lyrics: document.getElementById('lyrics'+mp3id).innerHTML ///TODO retrieve lyrics from server
			};

			// get title
			var els = songDetails.getElementsByTagName('span');
			if(els.length > 0)
			for(var j=0; j<els.length; j++)
			{
				if(els[j].className == 'title')
				{
					song.title = els[j].innerText;
					break;
				}
			}

			// get author
			var els = songDetails.getElementsByTagName('b');
			if(els.length > 0)
			{
				song.artist = els[0].innerText;
			}

			// get duration
			var els = songDetails.getElementsByTagName('div');
			if(els.length > 0)
			for(var j=0; j<els.length; j++)
			{
				if(els[j].className == 'duration')
				{
					song.duration = els[j].innerText;
					break;
				}
			}

			songs.push(song);
		}
	}

	safari.self.tab.dispatchMessage("found mp3s", songs);
}

if(document.location && document.location.host == 'vk.com')
{
	console.log('vkmus injected');

	safari.self.addEventListener("message", function(event){
		var evName = event.name;
		var evMsg  = event.message;

		if(evName == 'find vkmus')
		{
			console.log(evName, event);
			getLinks();
		}
		else if(evName == 'new location')
		{
			console.log(evName, event);
			document.location = evMsg;
		}
		else
		{
			console.warning('unknown event',event);
		}
	}, false);
}
